<template>
  <div class="dashboard-container">
    <!-- 页面标题和统计信息 -->
    <div class="dashboard-header">
      <div class="title-section">
        <h1 class="main-title">桥梁监控工作台</h1>
        <p class="subtitle">实时数据监控 | 预警分析 | 设备状态</p>
      </div>
      <div class="stats-cards">
        <div class="stat-card warning">
          <div class="stat-icon">
            <el-icon><Warning /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ statistics.currentWarnings }}</div>
            <div class="stat-label">当前预警</div>
          </div>
        </div>
        <div class="stat-card device">
          <div class="stat-icon">
            <el-icon><Monitor /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ statistics.totalDevices }}</div>
            <div class="stat-label">设备总数</div>
          </div>
        </div>
        <div class="stat-card health">
          <div class="stat-icon">
            <el-icon><DataAnalysis /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ statistics.healthScore }}</div>
            <div class="stat-label">健康评分</div>
          </div>
        </div>
        <div class="stat-card maintenance">
          <div class="stat-icon">
            <el-icon><Tools /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ statistics.maintenanceCount }}</div>
            <div class="stat-label">待保养设备</div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 主要内容区域 -->
    <div class="dashboard-content">
      <!-- 左侧：桥梁健康状态 -->
      <div class="left-column">
        <bridge-health-panel :data="healthData" />
        <sensor-status-panel :data="sensorData" />
      </div>
      
      <!-- 中间：桥梁实时监控与图表 -->
      <div class="center-column">
        <bridge-monitor-panel />
        <weather-panel :data="weatherData" />
      </div>
      
      <!-- 右侧：预警信息与任务 -->
      <div class="right-column">
        <warning-list-panel :data="warningList" />
        <maintenance-task-panel :data="maintenanceTasks" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { Warning, Monitor, DataAnalysis, Tools } from '@element-plus/icons-vue';

// 导入组件
import BridgeHealthPanel from './components/BridgeHealthPanel.vue';
import SensorStatusPanel from './components/SensorStatusPanel.vue';
import BridgeMonitorPanel from './components/BridgeMonitorPanel.vue';
import WeatherPanel from './components/WeatherPanel.vue';
import WarningListPanel from './components/WarningListPanel.vue';
import MaintenanceTaskPanel from './components/MaintenanceTaskPanel.vue';

// 定义接口
interface HealthComponent {
  name: string;
  score: number;
  status?: string;
}

interface HealthData {
  score: number;
  status?: string;
  lastCheckTime: string;
  components: HealthComponent[];
}

interface SensorCategory {
  name: string;
  total: number;
  online: number;
}

interface SensorData {
  total: number;
  online: number;
  offline: number;
  warning: number;
  categories: SensorCategory[];
}

interface WeatherForecast {
  date: string;
  condition: string;
  tempMax: number;
  tempMin: number;
  windSpeed: number;
}

interface WeatherData {
  location: string;
  current: {
    temperature: number;
    condition: string;
    humidity: number;
    windSpeed: number;
    windDirection: string;
  };
  forecast: WeatherForecast[];
}

interface WarningItem {
  id: string;
  title: string;
  createdAt: string;
  createTime?: string;
  content: string;
  type: string;
  level: string;
  status: string;
  deviceId: string | null;
}

interface MaintenanceTask {
  id: string;
  title: string;
  description: string;
  deviceId: string | null;
  deviceName: string;
  dueDate: string;
  completed: boolean;
  taskType: string;
  priority: string;
}

// 定义统计数据
const statistics = ref({
  currentWarnings: 3,
  totalDevices: 142,
  healthScore: 92,
  maintenanceCount: 5
});

// 健康数据
const healthData = ref<HealthData>({
  score: 92,
  lastCheckTime: new Date().toISOString(),
  components: [
    { name: '主梁', score: 95 },
    { name: '桥墩', score: 93 },
    { name: '桥面', score: 90 },
    { name: '伸缩缝', score: 85 },
    { name: '支座', score: 89 }
  ]
});

// 传感器数据
const sensorData = ref<SensorData>({
  total: 142,
  online: 138,
  offline: 4,
  warning: 2,
  categories: [
    { name: '应变传感器', online: 45, total: 48 },
    { name: '振动传感器', online: 36, total: 36 },
    { name: '位移传感器', online: 28, total: 30 },
    { name: '倾角传感器', online: 18, total: 18 },
    { name: '加速度传感器', online: 11, total: 12 }
  ]
});

// 天气数据
const weatherData = ref<WeatherData>({
  location: '舟山大桥区域',
  current: {
    temperature: 28,
    condition: 'sunny',
    humidity: 65,
    windSpeed: 32,
    windDirection: '东南风'
  },
  forecast: [
    { date: '05-30', condition: 'cloudy', tempMax: 32, tempMin: 24, windSpeed: 28 },
    { date: '05-31', condition: 'rainy', tempMax: 26, tempMin: 22, windSpeed: 35 },
    { date: '06-01', condition: 'rainy', tempMax: 25, tempMin: 21, windSpeed: 40 }
  ]
});

// 预警列表
const warningList = ref<WarningItem[]>([
  {
    id: 'W001',
    title: '支座位移预警',
    createdAt: new Date(Date.now() - 3600000).toISOString(),
    createTime: new Date(Date.now() - 3600000).toISOString(),
    content: '2号支座位移传感器数值超出预警阈值，当前值：312μm，阈值：300μm',
    type: 'displacement',
    level: 'medium',
    status: 'unprocessed',
    deviceId: 'S002'
  },
  {
    id: 'W002',
    title: '桥墩倾斜预警',
    createdAt: new Date(Date.now() - 7200000).toISOString(),
    createTime: new Date(Date.now() - 7200000).toISOString(),
    content: '3号桥墩倾角传感器数值异常，当前值：1.2°，阈值：1.0°',
    type: 'tilt',
    level: 'high',
    status: 'unprocessed',
    deviceId: 'T002'
  },
  {
    id: 'W003',
    title: '强风预警',
    createdAt: new Date(Date.now() - 1800000).toISOString(),
    createTime: new Date(Date.now() - 1800000).toISOString(),
    content: '预计未来12小时内有8-9级东南风，请注意桥梁安全',
    type: 'weather',
    level: 'medium',
    status: 'processing',
    deviceId: null
  }
]);

// 维护任务
const maintenanceTasks = ref<MaintenanceTask[]>([
  {
    id: 'M001',
    title: '传感器校准',
    description: '对2号支座位移传感器进行校准维护',
    deviceId: 'S002',
    deviceName: '2号支座位移传感器',
    dueDate: new Date(Date.now() + 86400000).toISOString(),
    completed: false,
    taskType: 'regular',
    priority: 'medium'
  },
  {
    id: 'M002',
    title: '桥墩检查',
    description: '检查3号桥墩倾斜情况，确认结构完整性',
    deviceId: 'T002',
    deviceName: '3号桥墩倾角传感器',
    dueDate: new Date(Date.now() + 43200000).toISOString(),
    completed: false,
    taskType: 'inspect',
    priority: 'high'
  },
  {
    id: 'M003',
    title: '传感器电池更换',
    description: '更换离线传感器的电池',
    deviceId: null,
    deviceName: '离线传感器(4个)',
    dueDate: new Date(Date.now() - 86400000).toISOString(),
    completed: false,
    taskType: 'maintenance',
    priority: 'medium'
  },
  {
    id: 'M004',
    title: '桥面裂缝修复',
    description: '修复桥面发现的微小裂缝',
    deviceId: null,
    deviceName: '桥面段2区域',
    dueDate: new Date(Date.now() + 604800000).toISOString(),
    completed: false,
    taskType: 'repair',
    priority: 'low'
  },
  {
    id: 'M005',
    title: '季度设备全检',
    description: '对所有监测设备进行季度全面检查',
    deviceId: null,
    deviceName: '全部设备',
    dueDate: new Date(Date.now() + 1209600000).toISOString(),
    completed: false,
    taskType: 'regular',
    priority: 'medium'
  }
]);

// 定时刷新数据
let refreshTimer: number | null = null;

// 获取统计数据
const fetchStatistics = () => {
  try {
    // 这里应该是实际的API调用
    console.log('Fetching statistics data...');
    // 模拟API响应
    const newWarningsCount = Math.floor(Math.random() * 2) + 2;
    statistics.value.currentWarnings = newWarningsCount;
  } catch (error) {
    console.error('获取统计数据失败:', error);
  }
};

// 获取传感器数据
const fetchSensorData = () => {
  try {
    // 这里应该是实际的API调用
    console.log('Fetching sensor data...');
    // 模拟API响应 - 随机更新在线设备数量
    const newOnline = sensorData.value.total - Math.floor(Math.random() * 5);
    sensorData.value.online = newOnline;
    sensorData.value.offline = sensorData.value.total - newOnline;
  } catch (error) {
    console.error('获取传感器数据失败:', error);
  }
};

// 获取预警列表
const fetchWarningList = () => {
  try {
    // 这里应该是实际的API调用
    console.log('Fetching warning list...');
    // 模拟API响应 - 可能添加新的预警
    if (Math.random() > 0.8) {
      const newWarning: WarningItem = {
        id: `W00${warningList.value.length + 1}`,
        title: '新增振动预警',
        createdAt: new Date().toISOString(),
        createTime: new Date().toISOString(),
        content: '桥梁中部振动传感器检测到异常振动',
        type: 'vibration',
        level: 'low',
        status: 'unprocessed',
        deviceId: 'V001'
      };
      warningList.value.unshift(newWarning);
    }
  } catch (error) {
    console.error('获取预警列表失败:', error);
  }
};

// 获取维护任务
const fetchMaintenanceTasks = () => {
  try {
    // 这里应该是实际的API调用
    console.log('Fetching maintenance tasks...');
    // 模拟API响应 - 不做实际更改
  } catch (error) {
    console.error('获取维护任务失败:', error);
  }
};

// 页面加载时获取数据
onMounted(() => {
  fetchStatistics();
  fetchSensorData();
  fetchWarningList();
  fetchMaintenanceTasks();
  
  // 设置定时刷新 - 每60秒刷新一次数据
  refreshTimer = window.setInterval(() => {
    fetchStatistics();
    fetchSensorData();
    fetchWarningList();
  }, 60000);
});

// 组件卸载时清除定时器
onUnmounted(() => {
  if (refreshTimer !== null) {
    clearInterval(refreshTimer);
  }
});
</script>

<style scoped lang="scss">
.dashboard-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
  
  .dashboard-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 24px;
    
    .title-section {
      .main-title {
        font-size: 24px;
        font-weight: 600;
        color: #303133;
        margin: 0 0 8px 0;
      }
      
      .subtitle {
        font-size: 14px;
        color: #909399;
        margin: 0;
      }
    }
    
    .stats-cards {
      display: flex;
      gap: 16px;
      
      .stat-card {
        display: flex;
        align-items: center;
        padding: 16px 20px;
        border-radius: 8px;
        background: white;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
        transition: transform 0.3s;
        
        &:hover {
          transform: translateY(-5px);
        }
        
        .stat-icon {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 48px;
          height: 48px;
          border-radius: 12px;
          margin-right: 16px;
          
          .el-icon {
            font-size: 24px;
            color: white;
          }
        }
        
        .stat-content {
          .stat-value {
            font-size: 24px;
            font-weight: 600;
            line-height: 1.2;
          }
          
          .stat-label {
            font-size: 14px;
            color: #606266;
          }
        }
        
        &.warning {
          .stat-icon {
            background-color: #f56c6c;
            background-image: linear-gradient(135deg, #f56c6c 0%, #e6a23c 100%);
          }
          
          .stat-value {
            color: #f56c6c;
          }
        }
        
        &.device {
          .stat-icon {
            background-color: #409eff;
            background-image: linear-gradient(135deg, #409eff 0%, #53a8ff 100%);
          }
          
          .stat-value {
            color: #409eff;
          }
        }
        
        &.health {
          .stat-icon {
            background-color: #67c23a;
            background-image: linear-gradient(135deg, #67c23a 0%, #95d475 100%);
          }
          
          .stat-value {
            color: #67c23a;
          }
        }
        
        &.maintenance {
          .stat-icon {
            background-color: #909399;
            background-image: linear-gradient(135deg, #909399 0%, #c0c4cc 100%);
          }
          
          .stat-value {
            color: #909399;
          }
        }
      }
    }
  }
  
  .dashboard-content {
    display: grid;
    grid-template-columns: 1fr 1.5fr 1fr;
    gap: 20px;
    
    .left-column,
    .center-column,
    .right-column {
      display: flex;
      flex-direction: column;
      gap: 20px;
    }
  }
}

@media (max-width: 1440px) {
  .dashboard-content {
    grid-template-columns: 1fr 1fr;
    
    .right-column {
      grid-column: span 2;
      display: grid !important;
      grid-template-columns: 1fr 1fr;
    }
  }
}

@media (max-width: 768px) {
  .dashboard-header {
    flex-direction: column;
    
    .stats-cards {
      margin-top: 16px;
      flex-wrap: wrap;
      
      .stat-card {
        flex: 1 1 calc(50% - 8px);
        min-width: calc(50% - 8px);
      }
    }
  }
  
  .dashboard-content {
    grid-template-columns: 1fr;
    
    .right-column {
      grid-column: auto;
      display: flex !important;
      flex-direction: column;
    }
  }
}
</style> 